<?php
	include_once("connect.php");
	include_once("post_model.php");
	include_once("tag_model.php");
	mysql_select_db("progin_171_13509047",$con);	
	session_start();	
	if(!isset($_SESSION["userid"])) {	
		header("location:index.php");
	}				
?>

<?php 
	
	$post_model = new Post_Model();
	$tag_model = new Tag_Model();
	
	$title='';
	$konten_link='';
	$deskripsi_link='';
	$youtube_link='';
	$tag='';
	$errorFlag = false;
	
	if(isset($_POST['submitted']) && $_POST['submitted']==1) {
	
		//samain dengan konten yang sebelumnya diisi(hanya konten yang diselek yang terjaga)
		if(isset($_POST['title']))
			$title = $_POST['title'];		
		if(isset($_POST['konten_link']))
			$konten_link = $_POST['konten_link'];
		if(isset($_POST['deskripsi_link']))
			$deskripsi_link = $_POST['deskripsi_link'];
		if(isset($_POST['youtube_link'])) 
			$youtube_link = $_POST['youtube_link'];
		if(isset($_POST['tag']))
			$tag = $_POST['tag'];			
		
		//validasi post title		
		$errors = array("title"=>"", "konten_link"=>"", "img_upload"=>"", "post_type"=>"", "tag"=>"");		
		if((isset($_POST['title']) && $_POST['title'] == "") || (!isset($_POST['title']))) {
			$errors['title'] .= "Post's title can't be empty ";
			$errorFlag = true;
		}
		
		//validasi link
		if((isset($_POST['pilihan']) && isset($_POST['konten_link']) && $_POST['pilihan']=='link' && !validateURL($_POST['konten_link'])) || (isset($_POST['pilihan']) && $_POST['pilihan']=='link' && !isset($_POST['konten_link']))) {
			$errors['konten_link'] .= " URL is invalid. Maybe you forgot to add the protocol";
			$errorFlag = true;
		}			

		//validasi konten image
		if((isset($_POST['pilihan']) && isset($_FILES['img_upload']) && $_POST['pilihan']=='image' && !validateImage($_FILES)) || (isset($_POST['pilihan']) && $_POST['pilihan']=='image' && !isset($_FILES['img_upload']))) {
			$errors['img_upload'] .= " only image(jpeg or jpg) is allowed to be uploaded and image must below 5 MB size";
			$errorFlag = true;			
		}		
		
		//validasi tag
		//remove leading dan trailing space nya dulu
		$tag = trim($tag);
		if(strlen($tag)==0) {
			$errors['tag'] .= " tag is empty"; 
			$errorFlag = true;
		}
		
		if(!isset($_POST['pilihan']) || (isset($_POST['pilihan']) && $_POST['pilihan']!='link' && $_POST['pilihan']!='image' && $_POST['pilihan']!='video')) {
			//jika tipe konten tidak dipilih
			$errors['post_type'] .= "You have to specify the content type ";			
			$errorFlag = true;
		}
		
		if(!$errorFlag && isset($_POST['pilihan']) && ($_POST['pilihan']=='link' || $_POST['pilihan']=='image' || $_POST['pilihan']=='video')) {
			//lolos validasi			
			$ret = insertPost($_POST['pilihan'], $post_model, $tag_model);	
			//redirect
			header("location:content.php?id=".$ret);
		}
	}
	
	function validateURL($url) {
		return filter_var($url, FILTER_VALIDATE_URL);					
	}
	
	function validateImage($file) {
		global $errors;
				
		if ((($_FILES["img_upload"]["type"] == "image/jpeg")
			|| ($_FILES["img_upload"]["type"] == "image/pjpeg"))
			&& ($_FILES["img_upload"]["size"] < 5 * 1024000)) // maksimum 5 mb
			{
				if ($_FILES["img_upload"]["error"] > 0) {
					$errors['img_upload'] .= " Error: " . $_FILES["img_upload"]["error"];
					return false;
				} else {
					return true;
				}
		}else{						
		  return false; 
		}
	}
	
	function filterTag($tag) {
		return explode(",", $tag);
	}
	
	function insertPost($post_type, $post_model, $tag_model) {				
		global $title, $konten_link, $deskripsi_link, $youtube_link, $tag;
		date_default_timezone_set('Asia/Jakarta');
		$date = date('m_d_Y_h_i_s_a', time());		
		$poster_id = $_SESSION["userid"];
		$arr_tag = filterTag($tag);
		
		//masukin tag-tagnya ke database dulu
		foreach($arr_tag as $key=>$element) {
			//escape
			$element = mysql_real_escape_string($element);
			//batesin panjang tiap tag sepanjang 20 karakter
			$element = substr($element, 0, 20);
			//trim leading dan trailing space
			$element = trim($element);			
			if(strlen($element)>0) {
				insertTag($element, $tag_model);
				$arr_tag[$key] = $element;
			}else{
				//buang dari $arr_tag
				unset($arr_tag[$key]);
			}
		}		
		
		if($post_type=='link') {
			$konten_link = mysql_real_escape_string($konten_link);
			$deskripsi_link = mysql_real_escape_string($deskripsi_link);
			$content = $konten_link.'\n'.$deskripsi_link;
		}else if($post_type=='image') {
			// pindahin ke folder upload dengan nama filenya adalah id user yang ngepost beserta tanggal & waktu-nya								
			$info = pathinfo($_FILES['img_upload']['name']);
			$content = $poster_id."_".$date.".".$info['extension'];//berisi filename
			move_uploaded_file($_FILES["img_upload"]["tmp_name"], 'upload/'.$content);			
		}else if($post_type=='video') {			
			$content = mysql_real_escape_string($youtube_link);			
		}								
		
		$post_id = $post_model->insertPost($title, $post_type, $poster_id, $content);
		
		//masukin relasi post dengan tag ke table post_tag 
		foreach($arr_tag as $aTag) {			
			insertPostTagType($post_id, $aTag, $tag_model);
		}	
		
		return $post_id;
	}
	
	//masukin satu tag ke database
	function insertTag($aTag, $tag_model) {				
		$ret = $tag_model->insertTag($aTag);		
		return $ret;
	}
	
	//masukin satu id post dengan tag_type ke table post_tag di db
	function insertPostTagType($post_id, $tag_type, $tag_model) {
		$res = $tag_model->getTagInfoByType($tag_type);				
		
		$row = mysql_fetch_array($res);		
		if($res!=false) {
			//ditemukan tag_type tersebut di tabel tag			
			insertPostTag($post_id, $row['ID'], $tag_model);			
		}
	}
	
	//masukin satu id post dan id tag ke table post_tag di db
	function insertPostTag($post_id, $tag_id, $tag_model) {
		$tag_model->insertPostTag($post_id, $tag_id);
	}
?>

<?php include_once("header.php"); ?>

	<!-- Body -->
	<div id="bodycontent">
	  <div class="contentcontainer">
	    
		<div class="title-text">
		  <h1>Posting Konten</h1>
		</div>
		
		<div class="contentbox">
			<form action="post.php" method="POST" enctype="multipart/form-data">
				<div class="form-element1">Judul konten:</div>
				<div class="form-element2"><input type="text" name="title" size="35" value="<?php echo (isset($_POST['title']) ? ($_POST['title']) : ("")) ?>" /><span class='form-error'> <?php echo (isset($errors['title']) ? ($errors['title']) : ("")); ?> </span></div>
				<br/>
				<div class="form-element1">Tipe konten: <span class='form-error'> <?php echo (isset($errors['post_type']) ? ($errors['post_type']) : ("")); ?> </span></div>
				<br/>
				<div class="form-element1"><input type="radio" name="pilihan" onclick="linkSelected()" value="link" <?php echo (isset($_POST['pilihan']) && $_POST['pilihan']=='link' ? "checked='checked'" : "") ?> /> Link </div>
				<br/>
				<div class="form-element1">Link :</div>
				<div class="form-element2"><input type="text" name="konten_link" <?php echo (isset($_POST['pilihan']) && $_POST['pilihan']=='link' ? "" : 'disabled="disabled"');  ?> size="35" value="<?php echo $konten_link; ?>" /><span class='form-error'> <?php echo (isset($errors['konten_link']) ? ($errors['konten_link']) : ("")); ?> </span></div>
				<br/>
				<div class="form-element1">Deskripsi :</div>
				<div class="form-element2"><input type="text" name="deskripsi_link" <?php echo (isset($_POST['pilihan']) && $_POST['pilihan']=='link' ? "" : 'disabled="disabled"');  ?>  size="35" value="<?php echo $deskripsi_link; ?>" /></div>
				<br/>
				<div class="form-element1"><input type="radio" name="pilihan" onclick="imageSelected()" value="image" <?php echo (isset($_POST['pilihan']) && $_POST['pilihan']=='image' ? "checked='checked'" : "") ?> /> Image </div>
				<br/>
				<div class="form-element1">Image Upload : </div>
				<div class="form-element2"><input type="file" name="img_upload" <?php echo (isset($_POST['pilihan']) && $_POST['pilihan']=='image' ? "" : 'disabled="disabled"');  ?>  size="35"/>  <span class='form-error'> <?php echo (isset($errors['img_upload']) ? ($errors['img_upload']) : ("")); ?> </span> </div>
				<br/>
				<div class="form-element1"><input type="radio" name="pilihan" onclick="videoSelected()" value="video" <?php echo (isset($_POST['pilihan']) && $_POST['pilihan']=='video' ? "checked='checked'" : "") ?> /> Video </div>
				<br/>
				<div class="form-element1">YouTube Link :</div>
				<div class="form-element2"><input type="text" name="youtube_link" <?php echo (isset($_POST['pilihan']) && $_POST['pilihan']=='video' ? "" : 'disabled="disabled"');  ?> value="<?php echo $youtube_link; ?>"  size="35"/></div>
				<br/>
				<div class="form-element1">Tag : </div>
				<div class="form-element2"><input type="text" name="tag" value="<?php echo $tag; ?>" /> <span class='form-error'> <?php echo (isset($errors['tag']) ? ($errors['tag']) : ("")); ?> </span> </div>
				<br/>
				<input type="hidden" name="submitted" value="1"> 
				<div class="form-element1"><input type="submit" id="post" value="post" /></div>				
			</form>
				
			<div class="form-element1"><input type="button" id="preview" value="preview" onclick="validate();" /></div>				
			<div id="post-hasil">
			</div>
		</div>		
	  </div>
	</div>

<?php
	include_once("footer.php");
	include_once("close_con.php");
?>
